<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keywords" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getDept">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" >
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" >
        <template scope="scope">
          <span v-if="scope.row.state=='-1'" style="color: red">停用</span>
          <span v-else-if="scope.row.state=='0'" style="color: green">正常</span>
          <span v-else style="color: gray">未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="employee.username" label="负责人" width="120" >
      </el-table-column>
      <el-table-column prop="parentDepartment.name" label="上级部门" min-width="180" >
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination :current-page="page" layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门编号" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="0">正常</el-radio>
						<el-radio class="radio" :label="-1">停用</el-radio>
					</el-radio-group>
				</el-form-item>
        &nbsp;&nbsp;&nbsp;负责人
				<el-select v-model="editForm.employee" value-key="id" filterable placeholder="请选择">
        <el-option
            v-for="item in employees"
            :key="item.id"
            :label="item.username"
            :value="item">
          <span style="float: left">{{ item.username }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
        </el-option>
      </el-select>
        <el-cascader
            v-model="editForm.parentDepartment"
            :disabled="disabled"
            :options="tree"
            :props="{ checkStrictly:true,label:'name',value:'id'}"
            clearable></el-cascader>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>


	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';
  import Employee from "./Employee";

	export default {
		data() {
			return {
				filters: {
          keywords: ''
				},
				depts: [],
        employees:[],
        tree:[],
        props:{
          label: 'name', //这里可以配置你们后端返回的属性
          value: 'id',
          checkStrictly: true
        },
        title:"",
				total: 0,
				page: 1,
        pageSize:5,
				listLoading: false,
        dataid:[],
        disabled:false,
				sels: [],//列表选中列
				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm:{

        },
			}
		},
		methods: {
			handleCurrentChange(val) {
				this.page = val;
				this.getDept();
			},
			//获取部门列表
			getDept() {
			  this.getTree();
        let query = {
          currentPage: this.page,
          keywords: this.filters.keywords
        }
        this.listLoading = true;
        this.$http.post("/dept",query).then(res=>{

          this.depts=res.data.rows;
          this.total=res.data.total;
        })
				this.listLoading = false;

			},
      getEmps(){
			  this.$http.get("/emp").then(res=>{
          this.employees=res.data;
        })
      },
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					//NProgress.start();
          this.$http.delete('dept/'+row.id).then( ()=>{
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.page=1;
						this.getDept();
					});
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {

        this.title="编辑"
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
				this.disabled=false;
        if(this.dataid.indexOf(this.editForm.id)==-1){
          this.disabled=true;
        }
        if(this.editForm.dirPath){
          let array= this.editForm.dirPath.split("/");
          let tmp=[];
          for(let i=1;i<array.length-1;i++){
            tmp.push(parseInt(array[i]))
          }
          this.editForm.parentDepartment=tmp

        }


			},
			//显示新增界面
			handleAdd: function () {
        this.title="新增"
				this.editFormVisible = true;
        this.disabled=false;
				this.editForm = {
				  id:null,
					username: '',
					sn: '',
					state: null,
          employee:null,
          dirPath:null,
				};
			},
			//编辑/新增
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
              console.log(para)
              if(para.parentDepartment){// [2,7]
                para.parentDepartment = {
                  "id": para.parentDepartment[para.parentDepartment.length - 1]
                }
              }

							this.$http.put('/dept',para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								// this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDept();
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
      //TREE
      getTree:function (){
        this.$http("/dept/tree").then(res=>{
          this.dataid=[]
          this.tree=res.data
          this.tree=this.getTreeData(this.tree)
        })
      },getTreeData(data) {

        // 循环遍历json数据
        for (var i = 0; i < data.length; i++) {

          if (data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            data[i].children = undefined;
            this.dataid.push(data[i].id)
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            this.getTreeData(data[i].children);
          }
        }

        return data;
      },
			//批量删除
			batchRemove: function () {

				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					//NProgress.start();
          this.$http.patch("/dept",ids).then((res) => {
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
            this.page=1;
              this.getDept();
					});
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getDept();
			this.getEmps();

		}
	}

</script>

<style scoped>

</style>